package com.googlecode.monitoria.client.gui;

import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormButtonBinding;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.CenterLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.googlecode.monitoria.client.Application;
import com.googlecode.monitoria.client.services.MonitoriaServiceAsync;

/**
 * Login screen.
 * @author Ricardo Araújo Santos - ricardo@lsd.ufcg.edu.br
 */
public class FirstRunScreen extends LayoutContainer {
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		setLayout(new CenterLayout());
		
		FormData formData = new FormData();
		
		final FormPanel simple = new FormPanel();  
	    simple.setHeading("Administrator registration!");  
	    simple.setFrame(true);  
	    simple.setWidth(350);
	    
	    final TextField<String> password = new TextField<String>();  
	    password.setFieldLabel("Password");
	    password.setPassword(true);
	    password.setAllowBlank(false);  
	    password.setData("aria-previous", simple.getButtonBar().getId());  
	    simple.add(password, formData);  
	    
	    Button b = new Button("Submit");
	    
	    b.addSelectionListener(new SelectionListener<ButtonEvent>() {
			@Override
			public void componentSelected(ButtonEvent ce) {
				if(!simple.isValid()){
					return;
				}
				registerAdmin(password.getValue());
			}
		});
	    
	    simple.addButton(b);

	    FormButtonBinding binding = new FormButtonBinding(simple);  
	    binding.addButton(b); 
	    Info.display("New", "content");
		add(simple);
	}
	
	protected void registerAdmin(String password) {
		MonitoriaServiceAsync.Util.getInstance().registerAdmin( password, new AsyncCallback<Void>() {
			
			public void onSuccess( Void result ) {
				Application.get().setLoginScreen();
			}
			
		
			public void onFailure( Throwable t ) {
				setErrorText( "Please, try again. Error: " + t.getMessage() );
			}
		});
	}
	
	protected void setErrorText(String error) {
		System.out.println(error);
	}
}
